class VersionsController < ApplicationController
  protect_from_forgery except: :index
  skip_before_action :verify_authenticity_token, :only => [:upload, :import]
  before_action :set_version, only: [:edit, :update, :destroy]
  def index
    @app_versions = Version.includes(:app).all
    respond_to do |format|
      format.html
      format.js
    end
  end

  def upload
    @preview_versions = []
    file = Roo::Excelx.new(params[:upload_excel_file].tempfile.path)
    rows = file.to_a[1..-1]
    rows.each do |row|
      version_temp = {}
      version_attributes.each_with_index do |attribute, index|
        cell_value = row[index].to_s.strip
        case attribute
        when 'app_id'
          version_temp['app_id'] = cell_value.to_i
        when 'version'
          version_temp['version'] = cell_value
        when 'success'
          version_temp['success'] = cell_value.to_i
        when 'fails'
          version_temp['fails'] = cell_value.to_i
        when 'typehood'
          version_temp['typehood'] = cell_value
        when 'source'
          version_temp['source'] = cell_value
        when 'description'
          version_temp['description'] = cell_value
        when 'released_date'
          version_temp['released_date'] = cell_value
        end
      end
      version = Version.new(version_temp)
      @preview_versions << version
    end
    @unknown_app = false
    @preview_versions.each do |version|
      if App.where(id: version.app_id).blank?
        @unknown_app = true
      end
    end
  end

  def import
    @versions = JSON.parse(params[:preview_versions].gsub("\r\n", " "))
    @versions.each{|version| Version.new(version).save}
    reload_versions
  end
  
  def sample
    send_file Rails.root.join('public','sample.xlsx')
  end

  def edit
  end

  def destroy
    @version.destroy
    reload_versions
  end

  def update
    @version.update(version_params)
    reload_versions
  end

  private
    def reload_versions
      redirect_to action: :index
    end

    def version_params
      params.require(:version).permit(:version, :success, :fails, :released_date, :dev_id,
        :source, :typehood, :description)
    end

    def set_version
      @version = Version.find(params[:id])
    end

    def version_attributes
      %w(app_id version success fails released_date source typehood description)
    end
end
